import csv
import numpy as np
import argparse
from pymoo.indicators.hv import HV

def read_csv_points(filename, skip_header=True):
    """读取 CSV，返回 numpy 数组"""
    data = []
    with open(filename, newline='') as f:
        reader = csv.reader(f)
        # 如果需要跳过表头，则跳过第一行
        if skip_header:
            next(reader, None)
        for row in reader:
            if not row:
                continue
            data.append(list(map(float, row)))
    return np.array(data)


def hypervolume_improvement(ref_csv, new_csv, ref_point=None):
    """
    计算new_csv相比ref_csv的超体积提升（Hypervolume Improvement）
    
    参数:
        ref_csv, new_csv: 文件名
        ref_point: (可选) 参考点，如果为 None 则自动确定
        
    返回:
        超体积提升值 hv2 - hv1
    """
    F1 = read_csv_points(ref_csv)
    F2 = read_csv_points(new_csv)

    if ref_point is None:
        max_vals = F1.max(axis=0)
        ref_point = max_vals * 1.5

    hv = HV(ref_point=ref_point)
    hv1 = hv.do(F1)
    hv2 = hv.do(np.concatenate((F1, F2), axis=0))

    return hv2 - hv1


# 使用示例:
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("ref_csv", help="Reference CSV file")
    parser.add_argument("new_csv", help="New CSV file to compare")
    parser.add_argument("--ref_point", nargs=3, type=float, help="Reference point (3 floats)", default=None)
    args = parser.parse_args()
    improvement = hypervolume_improvement(args.ref_csv, args.new_csv, args.ref_point)
    print(f"Hypervolume improvement: {improvement:.6f}")
